<?php
/**
 * Created by PhpStorm.
 * User: 44766
 * Date: 2018-11-25
 * Time: 18:08
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\BlackList;
use App\Models\Favorite;
use App\Models\History;
use App\Models\Position;
use App\Models\Member;
use App\Models\Tag;
use App\Models\Tagged;
use App\Services\TagService\TagService;
use Auth;
use Illuminate\Support\Collection;
use Request;

class MemberController extends ResourceController
{
    public function index()
    {
        $member = Auth::user();
        $this->showExt($member);
        return $this->package($member);
    }

    public function update()
    {
        $member = Auth::user();
        $member->fill(Request::all());
        $member->save();
        return $this->success();
    }

    public function tag()
    {
        $service = new TagService();
        $service->clean(Auth::user());
        $tags = Tag::whereIn('id', Request::get('tag_ids'))->get();
        foreach ($tags as $tag) {
            $service->add(Auth::user(), $tag);
        }
        return $this->success();
    }

    public function recommend2()
    {
        $filter_ids     = [];
        $favorite_tags  = collect();
        $favorite_posts = Position::with('tags')->whereHas('favorites', function ($member) {
            /** @var Favorite $member */
            $member->where('member_id', Auth::id());
        })->get();
        foreach ($favorite_posts as $post) {
            $favorite_tags = $favorite_tags->merge($post->tags);
            $filter_ids[]  = $post->id;
        }


        $history_tags  = collect();
        $history_posts = Position::with('tags')->whereHas('histories', function ($member) {
            /** @var History $member */
            $member->where('member_id', Auth::id());
        })->get();
        foreach ($history_posts as $post) {
            $history_tags = $history_tags->merge($post->tags);
        }

        $tags = [];
        foreach (Auth::user()->tags as $tagged) {
            if (!isset($tags[$tagged->tag_id])) {
                $tags[$tagged->tag_id] = 0;
            }
            $tags[$tagged->tag_id] += 30;
        }

        foreach ($favorite_tags as $tagged) {
            if (!isset($tags[$tagged->tag_id])) {
                $tags[$tagged->tag_id] = 0;
            }
            $tags[$tagged->tag_id] += 10;
        }
        foreach ($history_tags as $tagged) {
            if (!isset($tags[$tagged->tag_id])) {
                $tags[$tagged->tag_id] = 0;
            }
            $tags[$tagged->tag_id] += 2;
        }
        $tags    = array_sort($tags);
        $tag_ids = (array_keys($tags));

        if (!$tag_ids) {
            return $this->packageList([]);
        }
        $positions = Position::with(['tags.tag'])->whereHas('tags', function ($tag) use ($tag_ids) {
            /** @var Tagged $tag */
            $tag->whereIn('tag_id', $tag_ids);
        })->whereNotIn('positions.id', $filter_ids);

        $this->renderList($positions);

        $positions = $positions->get();


        foreach ($positions as $position) {
            $score     = 0;
            $tag_count = 0;
            foreach ($position->tags as $tagged) {
                if (isset($tags[$tagged->tag_id])) {
                    $score += $tags[$tagged->tag_id];
                    $tag_count++;
                }
            }
//            $score=round($score/$tag_count,2);
            $recommendation = round($score / 100, 2);
            $position->setAttribute('score', $score);
            $position->setAttribute('recommendation', $recommendation > 1 ? 1 : $recommendation);
        }
        $positions = $positions->sortByDesc('score')->values();
        return $this->packageList($positions);
    }

    public function recommend()
    {
        $member_id = Auth::id();
        $sql       = "select p.`id` from positions as p 
                      left join 
                      (
                        select a.module_id,sum(b.`value`) as `value`
                        from taggeds as a 
                        left join 
                          (
                            select tag_id,sum(`value`) as `value`
                              from 
                                (
                                SELECT tag_id,`value` FROM member_portrayals
                                    WHERE member_id = {$member_id}
                                UNION ALL
                                SELECT tag_id,30 FROM taggeds
                                    WHERE module_id = {$member_id} AND module_type = 'member'
                                ) as temp 
                            GROUP BY tag_id
                          ) as b 
                          on a.tag_id=b.tag_id 
                          where a.module_type='position'
                          GROUP BY module_id
                      ) as v
                      on p.id=v.module_id
                      where v.`value`>0
                      ORDER BY v.`value` desc limit 0,15";
        /** @var Collection $result */
        $result    = collect(\DB::select($sql))->map(function ($value) {
            return (array)$value;
        });
        $ids       =$result->pluck('id');
        $positions =Position::whereIn('id',$ids)->orderBy(\DB::raw('FIELD(`id`, '.($ids->implode(',')).')'));
        return $this->renderList($positions)->autoPage($positions);
    }

    public function favorite()
    {
        $list = Favorite::whereMemberId(Auth::id());
        return $this->renderList($list)->autoPage($list);
    }

    public function history()
    {
        $list = History::whereMemberId(Auth::id());
        return $this->renderList($list)->autoPage($list);
    }

    public function blackList()
    {
        $list = BlackList::whereMemberId(Auth::id());
        return $this->renderList($list)->autoPage($list);
    }
}